package cn.fzkj.gulimall.product.service.impl;

import cn.fzkj.gulimall.product.dao.AttrAttrgroupRelationDao;
import cn.fzkj.gulimall.product.dao.AttrDao;
import cn.fzkj.gulimall.product.entity.AttrAttrgroupRelationEntity;
import cn.fzkj.gulimall.product.entity.AttrEntity;
import cn.fzkj.gulimall.product.vo.AttrGroupAndCascadeAttrsVo;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import cn.fzkj.common.utils.PageUtils;
import cn.fzkj.common.utils.Query;

import cn.fzkj.gulimall.product.dao.AttrGroupDao;
import cn.fzkj.gulimall.product.entity.AttrGroupEntity;
import cn.fzkj.gulimall.product.service.AttrGroupService;
import org.springframework.util.CollectionUtils;


@Service("attrGroupService")
public class AttrGroupServiceImpl extends ServiceImpl<AttrGroupDao, AttrGroupEntity> implements AttrGroupService {

    @Autowired
    private AttrAttrgroupRelationDao relationDao;

    @Autowired
    private AttrDao attrDao;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<AttrGroupEntity> page = this.page(
                new Query<AttrGroupEntity>().getPage(params),
                new QueryWrapper<AttrGroupEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public PageUtils queryPage(Map<String, Object> params, Long catelogId) {
        QueryWrapper<AttrGroupEntity> wrapper = new QueryWrapper<>();
        String key = (String) params.get("key");
        if (StringUtils.isNotEmpty(key)){
            wrapper.and((obj)->{
                obj.eq("attr_group_id", key).or().like("attr_group_name", key);
            });
        }
        if (catelogId == 0){
            IPage<AttrGroupEntity> page = this.page(
                    new Query<AttrGroupEntity>().getPage(params),
                    wrapper
            );

            return new PageUtils(page);
        }else {
            wrapper.eq("catelog_id", catelogId);
            IPage<AttrGroupEntity> page = this.page(new Query<AttrGroupEntity>().getPage(params), wrapper);
            return new PageUtils(page);
        }
    }

    /** 查询catelogId分类下的分组及分组下关联的所有属性 */
    @Override
    public List<AttrGroupAndCascadeAttrsVo> getAttrGroupAndCascadeAttrByCatelogId(Long catelogId) {

        List<AttrGroupEntity> groupEntities = this.baseMapper.selectList(new QueryWrapper<AttrGroupEntity>().eq("catelog_id", catelogId));


        if (CollectionUtils.isEmpty(groupEntities)){
            return Collections.EMPTY_LIST;
        }
        Map<Long, AttrGroupEntity> attrGroupEntityMap = new HashMap<>();

        // 1、分组的map
        List<Long> attrGroupIds = groupEntities.stream().map(item -> {
            // 在这里将返回的分组信息封装成一个map，方便后面封装返回数据
            attrGroupEntityMap.put(item.getAttrGroupId(), item);
            return item.getAttrGroupId();
        }).collect(Collectors.toList());

        if (CollectionUtils.isEmpty(attrGroupIds)){
            return Collections.EMPTY_LIST;
        }

        // 拿到分组id【attrGroupIds】去pms_attr_attrgroup_relation表中查询出attr_id
        List<AttrAttrgroupRelationEntity> relationEntities = relationDao.selectList(
                new QueryWrapper<AttrAttrgroupRelationEntity>().in("attr_group_id", attrGroupIds)
        );

        if (CollectionUtils.isEmpty(relationEntities)){
            return Collections.EMPTY_LIST;
        }
        // 2、关联的map
        Map<Long, Long> relationEntityMap = new HashMap<>();
        List<Long> attrIds = relationEntities.stream().map(item -> {
            relationEntityMap.put(item.getAttrId(), item.getAttrGroupId());
            return item.getAttrId();
        }).collect(Collectors.toList());

        if (CollectionUtils.isEmpty(attrIds)) {
            // 没有属性，直接返回分组信息
            List<AttrGroupAndCascadeAttrsVo> ret = new ArrayList<>();
            groupEntities.forEach(entity -> {
                AttrGroupAndCascadeAttrsVo vo = new AttrGroupAndCascadeAttrsVo();
                BeanUtils.copyProperties(entity, vo);
                ret.add(vo);
            });
            return ret;
        }

        // 拿到attr_ids去pms_attr表中查询下面的数据
        List<AttrEntity> attrEntities = attrDao.selectList(new QueryWrapper<AttrEntity>().in("attr_id", attrIds));

        // 3、属性的map
        Map<Long, AttrEntity> attrEntityMap = new HashMap<>();
        if (!CollectionUtils.isEmpty(attrEntities)){
            attrEntities.forEach(item -> attrEntityMap.put(item.getAttrId(), item));
        }else {
            // 没有属性，直接返回分组信息
            List<AttrGroupAndCascadeAttrsVo> ret = new ArrayList<>();
            groupEntities.forEach(entity -> {
                AttrGroupAndCascadeAttrsVo vo = new AttrGroupAndCascadeAttrsVo();
                BeanUtils.copyProperties(entity, vo);
                ret.add(vo);
            });
            return ret;
        }

        // 用来帮助判断集合中是否有对应的group对象，如果有则直接将attr对象放进去，没有则new
        List<Long> groupIds = new ArrayList<>();
        // groupId 和 AttrGroupAndCascadeAttrsVo的对应关系，方便返回数据封装
        Map<Long, AttrGroupAndCascadeAttrsVo> helperRetMap = new HashMap<>();
        List<AttrGroupAndCascadeAttrsVo> ret = new ArrayList<>();
        // 封装返回数据
        for (AttrAttrgroupRelationEntity relationEntity : relationEntities) {
            AttrEntity attrEntity = attrEntityMap.get(relationEntity.getAttrId());
            AttrGroupEntity attrGroupEntity = attrGroupEntityMap.get(relationEntity.getAttrGroupId());

            if (groupIds.contains(attrGroupEntity.getAttrGroupId())){
                helperRetMap.get(attrGroupEntity.getAttrGroupId()).getAttrs().add(attrEntity);
            }else {
                List<AttrEntity> attrs = new ArrayList<>();
                attrs.add(attrEntity);
                AttrGroupAndCascadeAttrsVo vo = new AttrGroupAndCascadeAttrsVo();
                BeanUtils.copyProperties(attrGroupEntity, vo);
                vo.setAttrs(attrs);
                groupIds.add(attrGroupEntity.getAttrGroupId());
                helperRetMap.put(attrGroupEntity.getAttrGroupId(), vo);
                ret.add(vo);
            }
        }
        return ret;
    }

}